package com.vnp.vchat;

import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;

import javax.net.ssl.SSLContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.TransitionDrawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.utils.L;
import com.telpoo.frame.net.BaseNetSupportBeta;
import com.telpoo.frame.net.NetConfig;
import com.telpoo.frame.utils.Mlog;
import com.vnp.vchat.bean.ObjContact;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.bean.ObjMsgChat;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.fragment.CaidatScr;
import com.vnp.vchat.fragment.DanhbaScr;
import com.vnp.vchat.fragment.KetnoiScr;
import com.vnp.vchat.fragment.KhachhangScr;
import com.vnp.vchat.fragment.TinNhanScr;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;
import com.vnp.vchat.util.Common;
import com.vnp.vchat.util.PreferenceHelper;
import com.vnp.vchat.util.Utils;
import com.vnp.vchat.version2.ChatNewActivity;
import com.vnp.vchat.view.TabIcon;

public class MainPanelActivity extends FragmentActivity implements OnClickListener, OnPageChangeListener {

	// static TabHost tabHost;
	PreferenceHelper preferenceHelper;
	Boolean backAgain = false;

	public static boolean isRunningApp = false;

	ViewPager viewPager;
	MyAdapter adapter;

	SocketIO socketIO;
	String URL = "http://w41.vnpgroup.net:8080";
	// String URL = "";

	MediaPlayer mp;
	MySQLiteHelper db;
	//boolean onPause = false;
	boolean onFinish = false;
	public static boolean onGoto = false;

	Handler mHandler = new Handler();

	// new msg
	ViewGroup viewNewMsg;
	TextView txtName, txtTinNhan;
	public static boolean isExit;
	private static MainPanelActivity me;
	private boolean isCheckingConnect=false; // true= ko cho check ket noi vi dang check

	Runnable rShow = new Runnable() {

		@Override
		public void run() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					viewNewMsg.setVisibility(View.VISIBLE);
					viewNewMsg.startAnimation(pullDown);
				}
			});
		}
	};

	Runnable rHide = new Runnable() {

		@Override
		public void run() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					viewNewMsg.setVisibility(View.INVISIBLE);
					viewNewMsg.startAnimation(pullUp);
				}
			});

		}
	};

	Animation pullDown, pullUp;
	Thread tr;


	

	// gui intent disconnect
	private BroadcastReceiver mReceiver;

	// getContact
	ArrayList<ObjContact> objContacts = new ArrayList<ObjContact>();
	JSONObject jsonPhone = new JSONObject();
	String listContactJson;
	String type;
	TextView tv_stn;
	LinearLayout ll_stn;
	ArrayList<String> list = new ArrayList<String>();

	TabIcon tab1, tab2, tab3, tab4, tab5;
	String value;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_panel);
		me = MainPanelActivity.this;
		

		tab1 = (TabIcon) findViewById(R.id.tab1);
		tab2 = (TabIcon) findViewById(R.id.tab2);
		tab3 = (TabIcon) findViewById(R.id.tab3);
		tab4 = (TabIcon) findViewById(R.id.tab4);
		tab5 = (TabIcon) findViewById(R.id.tab5);

		tab1.setOnClickListener(this);
		tab2.setOnClickListener(this);
		tab3.setOnClickListener(this);
		tab4.setOnClickListener(this);
		tab5.setOnClickListener(this);

		tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan);
		tab2.setBackgroundResource(R.drawable.ic_danhba);
		tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi);
		tab4.setBackgroundResource(R.drawable.ic_khach_hang);
		tab5.setBackgroundResource(R.drawable.tab_cai_dat);

		viewPager = (ViewPager) findViewById(R.id.pager);
		adapter = new MyAdapter(getSupportFragmentManager());
		viewPager.setAdapter(adapter);
		viewPager.setOnPageChangeListener(this);
		viewPager.setPageMargin(2);
		viewPager.setOffscreenPageLimit(5);

		viewNewMsg = (ViewGroup) findViewById(R.id.ll_new_msg);
		txtName = (TextView) findViewById(R.id.txt_name);
		txtTinNhan = (TextView) findViewById(R.id.txt_msg);
		pullDown = AnimationUtils.loadAnimation(this, R.anim.slide_down);
		pullUp = AnimationUtils.loadAnimation(this, R.anim.slide_up);

		isExit = true;
		// check ket noi socket
		tv_stn = (TextView) findViewById(R.id.tv_stn);
		ll_stn = (LinearLayout) findViewById(R.id.ll_stn);

		preferenceHelper = new PreferenceHelper(this);
		db = new MySQLiteHelper(MainPanelActivity.this);

		updateDeviceId();

		connectSocket();
		reciveBroadCast();
		setFont();
		L.disableLogging();
		// Xử lý lấy contact từ máy cập nhật vào db
		long t = Common.getCurrentTime() - preferenceHelper.getTimeGetContact();
		if (t > (1 * 60 * 60 * 1000)) {

			new Thread(new Runnable() {

				@Override
				public void run() {
					ArrayList<String> list = db.getPhoneFromDB();
					Utils.getContact(MainPanelActivity.this, 50, list.size());
					preferenceHelper.setTimeGetContact(System.currentTimeMillis());
				}
			}).start();
		}
		chuyentab(0);
		// setChecked(0);

		try {
			NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			nMgr.cancel(Common.NOTI_CODE);
		} catch (Exception e) {
		}

		if (Common.ojGcm != null) {
			Mlog.D("co du lieu gcm");
			mHandler.removeCallbacks(checkConnect);
			mHandler.postDelayed(checkConnect, 3000);
			mHandler.removeCallbacks(rHide);
			mHandler.postDelayed(rHide, 200);
			MainPanelActivity.onGoto = true;
			Intent t1 = new Intent(MainPanelActivity.this, ChatNewActivity.class);
			t1.putExtra("khachhang", Common.ojGcm);
			startActivity(t1);

			Common.ojGcm = null;

		}

	}

	

	Runnable checkConnect = new Runnable() {

		@Override
		public void run() {
			try {
				if (socketIO == null || !socketIO.isConnected()) {
					connectSocket();
				} else {
				}
				mHandler.postDelayed(checkConnect, 3000);
			} catch (Exception e) {
			}
		}
	};
	private boolean isConnectingSocket=false;

	private void setFont() {
		txtName.setTypeface(Utils.getTypefaceRegular(MainPanelActivity.this));
		txtTinNhan.setTypeface(Utils.getTypefaceRegular(MainPanelActivity.this));
	}

	private void playRingtone() {
		// Đây là ringtone mặc địch
		/*
		 * try { mp.prepare(); } catch (IllegalStateException e) {
		 * e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
		 * mp.start();
		 */
		/*
		 * Uri notification =
		 * RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		 * Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
		 * notification); r.play();
		 */

		mp = MediaPlayer.create(MainPanelActivity.this, R.raw.result);
		try {
			if (mp.isPlaying()) {
				mp.stop();
				mp.release();
				mp = MediaPlayer.create(MainPanelActivity.this, R.raw.result);
			}
			mp.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void updateMessager(int count) {
		if (count > 0) {
			ll_stn.setVisibility(View.VISIBLE);
			tv_stn.setText(String.valueOf(count));
		} else {
			ll_stn.setVisibility(View.GONE);
		}
	}

	private void showAnimationNewMsg(String name, String content) {
		mHandler.postDelayed(rShow, 300);
		txtName.setText(name);
		txtTinNhan.setText(content);
		mHandler.postDelayed(rHide, 3300);
	}

	@Override
	protected void onPause() {
		super.onPause();
		Common.appRunning = false;
		stopAutoConnect();
		Log.i("Socket", "ON PAUSE-----");

		StopSocket();

		cancelHandler();
	}

	

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		super.onResume();
		
		String timeexit= com.telpoo.frame.utils.Utils.getStringSPR("timeexit", me);
		Long timee=0l;
		try {
			 timee= Long.parseLong(timeexit);
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		Mlog.D("Calendar.getInstance().getTimeInMillis()- timee="+(Calendar.getInstance().getTimeInMillis()- timee)
);		
		if(Calendar.getInstance().getTimeInMillis()- timee<200)
			finish();
		
		Common.appRunning = true;
		if (socketIO != null)
			Log.i("Socket", "ON RESUME-----socketIO.isConnected()=" + socketIO.isConnected());
		//Log.i("Socket", "ONFISH: " + onFinish + " ONGOTO: " + onGoto + " ONPAUSE: " + onPause);
		isRunningApp = true;
		if (socketIO != null && !socketIO.isConnected())
			connectSocket();
		mHandler.removeCallbacks(checkConnect);
		mHandler.postDelayed(checkConnect, 3000);
	}

	public void connectSocket() {
		
		Log.i("Socket", "connectSocket() isConnectingSocket="+isConnectingSocket);
		if(isConnectingSocket)return;
		
		isConnectingSocket=true;
		runOnUiThread(new Runnable() {

			@Override
			public void run() {

				if (Common.onScreenChat == true) {
					// send broadcast show dang ket noi
					Intent broadcastIntent = new Intent();
					broadcastIntent.setAction(Common.CONNECTTING);
					sendBroadcast(broadcastIntent);
				}
			}
		});

		tr = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					socketIO = new SocketIO(URL);
					try {
						SocketIO.setDefaultSSLSocketFactory(SSLContext.getInstance("Default"));
					} catch (NoSuchAlgorithmException e1) {
						e1.printStackTrace();
					}

					
//					if (socketIO == null) {
//						
//					}
					socketIO.connect(new IOCallback() {

						@Override
						public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
							Log.i("DATA", "nhay vao thang 1");
						}

						@Override
						public void onMessage(String arg0, IOAcknowledge arg1) {
							Log.i("DATA", "nhay vao thang 2");
						}

						@Override
						public void onError(SocketIOException message) {
							isConnectingSocket=false;
							Log.e("Socket", "ket noi bi loi----------:" + message.toString());
							if (tr != null) {
								tr.interrupt();
							}
						}

						@Override
						public void onDisconnect() {
							isConnectingSocket=false;
							Log.e("Socket", "Da dut ket noi----------");
							if (Common.appRunning) {
								
								//connectSocket();
								startSocket();
							}
						}

						@Override
						public void onConnect() {
							isConnectingSocket=false;
							Log.e("Socket", "Ket noi thanh cong----------");
							socketIO.emit("join", preferenceHelper.getDataJoin());
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									if (Common.onScreenChat == true) {
										// send broadcast da kn
										Intent broadcastIntent = new Intent();
										broadcastIntent.setAction(Common.CONNECTED);
										sendBroadcast(broadcastIntent);
									}
								}
							});
						}

						@Override
						public void on(String event, IOAcknowledge arg1, Object... args) {
							Log.e("Socket", "on() event=" + event);

							String[] dataBroad = { event, args[0].toString() };

							Intent newMsg1 = new Intent();
							newMsg1.setAction(Common.HAVE_MESSAGE);
							newMsg1.putExtra("data", dataBroad);
							sendBroadcast(newMsg1);

							Object[] arguments = args;

							if (event.equals("chat")) {
								String json = arguments[0].toString();
								Log.i("vChat", "Json chat nhan dc: " + json.toString());
								try {
									JSONObject jos = new JSONObject(json);

									JSONObject jo = jos.getJSONObject("data");

									int sendId = jo.getInt("send_id");
									int id = jo.getInt("id");
									long vgc = jo.getLong("vgc_rand");

									if (Common.VGC == 0) {
										Common.VGC = Common.getCurrentTime();
									}

									Log.i("DATA", "VGC nhan dc: " + vgc + " VGC da gui: " + Common.VGC);
									// check vcg xem da co chua, neu co roi thi
									// khong lam gi ca, tuong tu nhu cai sendid

									if (Common.VGC == vgc) {
										// if
										// (preferenceHelper.getUserId().equals(String.valueOf(sendId))){
										Log.i("DATA", "lap message-----------");
									} else {
										final String name = jo.getString("name");
										final String content = jo.getString("text");
										int time = jo.getInt("time");

										String type, urlImage;
										if (jo.has("type")) {
											type = jo.getString("type");
											urlImage = content;
											if (type.equals("image")) {
												type = "image";
												urlImage = content;
											} else {
												type = "text";
												urlImage = "";
											}

										} else {
											type = "text";
											urlImage = "";
										}
										// nguyen nhan co the laf o cho nay
										String avatar = "";
										Log.i("DATA", "USER ID: " + preferenceHelper.getUserId() + " SendID: " + sendId);
										if (preferenceHelper.getUserId().equals(String.valueOf(sendId))) {
											Log.i("DATA", "0--------------------");
										} else {
											Log.i("DATA", "0---------66666666666");
											// avatar =
											// db.getUrlAvatar(String.valueOf(sendId));
										}

										Log.i("DATA", "1--------------------");

										ObjMsgChat objMsgChat = new ObjMsgChat();
										objMsgChat.setUrlImageKH(urlImage);
										objMsgChat.setFromId(String.valueOf(sendId));
										objMsgChat.setContent(content);
										objMsgChat.setUrlAvatarKhachhang(avatar);
										objMsgChat.setTenKhachHang(name);
										objMsgChat.setTime(time);
										objMsgChat.setType(type);
										objMsgChat.setId(String.valueOf(id));

										Log.i("DATA", "2--------------------");

										final ObjKhachhang objKhachhang = new ObjKhachhang();
										objKhachhang.setUrlAvatar(avatar);
										objKhachhang.setName(name);
										objKhachhang.setAddress("");
										objKhachhang.setDsDaxem("");
										objKhachhang.setId(String.valueOf(sendId));
										objKhachhang.setTxtWebsite("");
										objKhachhang.setOnline(1);
										objKhachhang.setUrlDangxem("");
										objKhachhang.setTimeLastMessage(String.valueOf(time));
										objKhachhang.setLastMessage(content);
										String msgId = String.valueOf(Common.getCurrentTime() / 1000);
										db.insertMSG(objMsgChat, objMsgChat.getFromId(), Common.SENDED, msgId);

										Log.i("vChat", "Co o trong man hinh chat :" + Common.onScreenChat);

										if (Common.onScreenChat == true) {
											Log.i("DATA", "IS CHATTING: " + Common.isChatting);
											if (Common.isChatting.equals(objMsgChat.getFromId())) {
												// gui 1 broad cast cho thang
												// msg
												Intent broadcastIntent = new Intent();
												broadcastIntent.setAction(Common.CHAT);
												sendBroadcast(broadcastIntent);
												db.updateLastMsg(objMsgChat, 0);

											} else {
												// xu li ds theiet bi tsi day
												if (preferenceHelper.getUserId().equals(String.valueOf(sendId))) {
													if (Common.isChatting.equals(objMsgChat.getId())) {
														Log.i("DATA", "Xu li add msg cua chinh minh tai day");
														db.insertMSG(objMsgChat, Common.isChatting, Common.SENDED, msgId);
														// gui 1 broad cast cho
														// thang msg
														Intent broadcastIntent = new Intent();
														broadcastIntent.setAction(Common.MY_ADD);
														sendBroadcast(broadcastIntent);
														db.updateLastMsg(objMsgChat, 1);
													} else {

													}

												} else {
													// gui 1 broad cast cho
													// thang msg
													Intent newMsg = new Intent();
													newMsg.putExtra("objMsg", objMsgChat);
													newMsg.putExtra("khachhang", objKhachhang);
													newMsg.setAction(Common.CHAT_NEWMSG);
													sendBroadcast(newMsg);
													db.updateLastMsg(objMsgChat, 1);
													Log.i("vChat", "send chat new msg cua nguoi dang ko chat");
												}
											}
										} else {
											if (preferenceHelper.getUserId().equals(String.valueOf(sendId))) {
												db.updateLastMsg(objMsgChat, 1);
												Intent broadcastIntent = new Intent();
												broadcastIntent.setAction(Common.IS_RELOAD);
												sendBroadcast(broadcastIntent);
											} else {
												runOnUiThread(new Runnable() {
													@Override
													public void run() {
														mHandler.removeCallbacks(rHide);
														mHandler.removeCallbacks(rShow);

														if (viewNewMsg.getVisibility() == View.VISIBLE) {
															viewNewMsg.setVisibility(View.GONE);
														}

														showAnimationNewMsg(name, content);
														if (preferenceHelper.getSettingRingtone() == 1) {
															playRingtone();
														}
													}
												});

												viewNewMsg.setOnClickListener(new OnClickListener() {

													@Override
													public void onClick(View v) {
														Log.i("vChat", "Click vo thang moi");
														mHandler.removeCallbacks(rHide);
														mHandler.postDelayed(rHide, 200);
														MainPanelActivity.onGoto = true;
														Intent t = new Intent(MainPanelActivity.this, ChatNewActivity.class);
														t.putExtra("khachhang", objKhachhang);
														startActivity(t);
													}
												});

												db.updateHischat(objKhachhang);

												Intent t = new Intent();
												t.setAction(Common.ADD);
												sendBroadcast(t);

												db.updateLastMsg(objMsgChat, 1);

												Intent newMsg = new Intent();
												newMsg.setAction(Common.IS_READ);
												sendBroadcast(newMsg);

												Log.i("vChat", "update trang thai chua doc cho msg");
											}
										}
									}

								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}

							if (event.equals("supplier")) {
								Log.i("vChat", "Supplier-----------------");
								String json = arguments[0].toString();
								Log.i("vChat", json.toString());
								try {
									JSONObject jos = new JSONObject(json);
									JSONObject data = jos.getJSONObject("data");

									int uid = data.getInt("uid");

									// khong tra ve uname
									String uname, avatar, city, pname, urlDangxem;
									if (data.has("uname")) {
										if (!data.getString("uname").equals("")) {
											uname = data.getString("uname");
										} else {
											uname = "Khách - " + String.valueOf(uid);
										}
									} else {
										uname = "Khách - " + String.valueOf(uid);
									}

									if (data.has("avatar")) {
										if (!data.getString("avatar").equals("")) {
											avatar = data.getString("avatar");
										} else {
											avatar = "";
										}
									} else {
										avatar = "";
									}

									if (data.has("city")) {
										if (!data.getString("city").equals("")) {
											city = data.getString("city");
										} else {
											city = data.getString("ip");
										}
									} else {
										city = data.getString("ip");
									}

									String txtWebsite = data.getString("source");

									String txtWebsiteR = txtWebsite.replace("www.", "");

									if (data.has("pname")) {
										if (!data.getString("pname").equals("")) {
											pname = data.getString("pname");
											urlDangxem = data.getString("url");
										} else {
											pname = "";
											urlDangxem = data.getString("url");
										}
									} else {
										pname = "";
										urlDangxem = data.getString("url");
									}

									urlDangxem = data.getString("url");

									ObjKhachhang objKhachhang = new ObjKhachhang();

									objKhachhang.setUrlAvatar(avatar);
									objKhachhang.setName(uname);
									objKhachhang.setAddress(city);
									objKhachhang.setDsDaxem(pname);
									objKhachhang.setId(String.valueOf(uid));
									objKhachhang.setTxtWebsite(txtWebsiteR);
									objKhachhang.setOnline(1);
									objKhachhang.setUrlDangxem("http://" + txtWebsite + urlDangxem);

									int size = db.getUID(objKhachhang.getId()).size();
									ArrayList<String> listUid = db.getUID(objKhachhang.getId());

									Log.i("vChat", "So ban ghi:" + size);
									Log.i("vChat", "ID khach hang: " + objKhachhang.getId());

									for (int i = 0; i < listUid.size(); i++) {
										if (objKhachhang.getId().equals(listUid.get(i))) {
											db.deleteKH(objKhachhang.getId());
											Log.i("vChat", "Xoa de update");
											// db.insertKH(objKhachhang,
											// objKhachhang.getId());
										}
									}

									db.insertKH(objKhachhang, String.valueOf(uid));
									Log.i("vChat", "Insert moi");

									// gui 1 broad cast cho thang kh
									Intent broadcastIntent = new Intent();
									broadcastIntent.setAction("com.app.vchat.REFRESH");
									sendBroadcast(broadcastIntent);

								} catch (Exception e) {
									e.printStackTrace();
								}

							}
						}
					});
				} catch (MalformedURLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
		});

		tr.start();
	}

	private void updateDeviceId() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler() {

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				Log.i("vChat", "Khong update duoc");
			}

			@Override
			public void onSuccess(JSONObject re) {
				Log.i("DATA", "Update device: " + re.toString());
				try {
					String error = re.getString("error");
					if (error.equals("")) {
						Log.i("vChat", "Update device thanh cong---------------s");
					} else {
						Log.i("vChat", "Update device that bai");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});

		httpClientHelper.updateDeviceID(Integer.valueOf(preferenceHelper.getUserId()), preferenceHelper.getHash(), "ANDROID", preferenceHelper.getDeviceId(),
				Utils.getIMEI(MainPanelActivity.this));
	}

	@Override
	public void onBackPressed() {
		if (backAgain == false) {
			
			Toast.makeText(MainPanelActivity.this, "Bấm lần nữa để thoát", 0).show();
			backAgain = true;
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					backAgain = false;
				}
			}, 2000);
		} else {
			backAgain = false;
			com.telpoo.frame.utils.Utils.saveStringSPR("timeexit", ""+Calendar.getInstance().getTimeInMillis(), me);
			finish();
			
		}
		
		
		isExit = true;
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onDestroy() {
		super.onDestroy();
		me = null;
		cancelHandler();
		onFinish = true;
		isRunningApp = false;
		if (tr != null) {
			try {
				tr.interrupt();
			} catch (Exception e) {
			}
		}

		try {
			mp.release();
		} catch (Exception e) {
			e.printStackTrace();
		}

		unregisterReceiver(mReceiver);

		if (isExit == true) {
			Log.i("DATA", "thoat he thong hoan toan");
			System.exit(0);
			isExit = false;
		} else {

		}
		// System.exit(0);
		Log.i("vChat", "ONDESTROY");
	}

	@Override
	protected void onStop() {
		super.onStop();

		Log.i("Socket", "onStop");
	}

	private void cancelHandler() {
		// mHandler.removeCallbacks(rHide);
		// mHandler.removeCallbacks(rShow);
		// mHandler.removeCallbacks(rHideKetnoi);
		// mHandler.removeCallbacksAndMessages(null);
	}

	private void reciveBroadCast() {
		IntentFilter intentFilter = new IntentFilter();

		intentFilter.addAction(Common.DISCONECT);
		intentFilter.addAction(Common.CONNECT);
		intentFilter.addAction("THOAT");

		mReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, final Intent intent) {
				String action = intent.getAction();
				if (action.equals(Common.DISCONECT)) {
					socketIO.disconnect();
					ChatNewActivity.onShow = false;
					Log.i("vChat", "Nhan duoc broadcast disconnect");
				} else if (action.equals(Common.CONNECT)) {
					if (tr != null) {
						tr.interrupt();
					}
					connectSocket();
					Log.i("vChat", "Nhan duoc broadcast connect");
				} else if (action.equals("THOAT")) {
					finish();
				}

			}
		};

		// register
		this.registerReceiver(mReceiver, intentFilter);
	}

	// demo getAccount by phone
	public void getAccount(String phone) {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler() {

			@Override
			public void onFailure(Throwable error) {
				Log.i("DATA", "GET ACCOUNT: " + error.toString());
			}

			@Override
			public void onSuccess(JSONObject re) {
				Log.i("DATA", "GET ACCOUNT: " + re.toString());
			}

		});

		httpClientHelper.getAccountByPhone(phone);
	}

	void getContact() {
		ContentResolver cr = getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		JSONArray block = new JSONArray();// clear phone list
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {

				ObjContact objContact = new ObjContact();

				String id = cur.getString(cur.getColumnIndex(BaseColumns._ID));
				String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

					Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
							new String[] { id }, null);
					String result = null;
					while (pCur.moveToNext()) {
						String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						result = phoneNo.replaceAll("\\(", "").replaceAll(" ", "").replaceAll("\\)", "").replaceAll("-", "").replace("+", "");

						block.put(result);
						objContact.setPhone(result);

					}
					pCur.close();
					pCur = null;

					/*
					 * objContact.setId(id); objContact.setName(name);
					 * 
					 * objContacts.add(objContact);
					 */
					list.add(result);

				}
			}
			

			sendContactHttp();

		} else {
			Log.i("CONTACT", "KHONG CO LIEN LAC");
		}
		cur.close();
		cur = null;
	}

	void sendContactHttp() {
		list = db.getPhoneFromDB();
		JSONArray jsonArray = new JSONArray(list);
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler() {

			@Override
			public void onFailure(Throwable error) {
				Log.i("DATA", "Cap nhat danh ba loi");
			}

			@Override
			public void onSuccess(JSONObject re) {
				Log.i("DATA", "Cap nhat danh ba thanh cong :" + re.toString());
			}
		});
		httpClientHelper.sendContact(preferenceHelper.getAdminId(), jsonArray, preferenceHelper.getHashSetting());
	}

	// Đổi màu tab icon khi chuyển tab.
	public void chuyentab(int id) {
		boolean animation = false;
		if (id == 0) {
			boolean is_check_imgtb1 = false;
			if (is_check_imgtb1 == true) {
				tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan);
				tab2.setBackgroundResource(R.drawable.ic_danhba);
				tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi);
				tab4.setBackgroundResource(R.drawable.ic_khach_hang);
				tab5.setBackgroundResource(R.drawable.tab_cai_dat);
				is_check_imgtb1 = false;
			} else {
				tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan_press);
				tab2.setBackgroundResource(R.drawable.ic_danhba);
				tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi);
				tab4.setBackgroundResource(R.drawable.ic_khach_hang);
				tab5.setBackgroundResource(R.drawable.tab_cai_dat);
				is_check_imgtb1 = true;
			}
			viewPager.setCurrentItem(0, animation);
		}
		if (id == 1) {
			boolean is_check_imgtb2 = false;
			if (is_check_imgtb2 == true) {
				tab2.setBackgroundResource(R.drawable.ic_danhba);
				tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan);
				tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi);
				tab4.setBackgroundResource(R.drawable.ic_khach_hang);
				tab5.setBackgroundResource(R.drawable.tab_cai_dat);
				is_check_imgtb2 = false;
			} else {
				tab2.setBackgroundResource(R.drawable.ic_danhba_press);
				tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan);
				tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi);
				tab4.setBackgroundResource(R.drawable.ic_khach_hang);
				tab5.setBackgroundResource(R.drawable.tab_cai_dat);
				is_check_imgtb2 = true;
			}
			viewPager.setCurrentItem(1, animation);
		}
		if (id == 2) {
			boolean is_check_imgtb3 = false;
			if (is_check_imgtb3 == true) {
				tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan);
				tab2.setBackgroundResource(R.drawable.ic_danhba);
				tab4.setBackgroundResource(R.drawable.ic_khach_hang);
				tab5.setBackgroundResource(R.drawable.tab_cai_dat);
				tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi);
				is_check_imgtb3 = false;
			} else {
				tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi_press);
				tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan);
				tab4.setBackgroundResource(R.drawable.ic_khach_hang);
				tab2.setBackgroundResource(R.drawable.ic_danhba);
				tab5.setBackgroundResource(R.drawable.tab_cai_dat);
				is_check_imgtb3 = true;
			}
			viewPager.setCurrentItem(2, animation);

		}
		if (id == 3) {
			boolean is_check_imgtb4 = false;
			if (is_check_imgtb4 == true) {
				tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan);
				tab2.setBackgroundResource(R.drawable.ic_danhba);
				tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi);
				tab4.setBackgroundResource(R.drawable.ic_khach_hang);
				tab5.setBackgroundResource(R.drawable.tab_cai_dat);
				is_check_imgtb4 = false;
			} else {
				tab4.setBackgroundResource(R.drawable.ic_khach_hang_press);
				tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan);
				tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi);
				tab2.setBackgroundResource(R.drawable.ic_danhba);
				tab5.setBackgroundResource(R.drawable.tab_cai_dat);
				is_check_imgtb4 = true;
			}
			viewPager.setCurrentItem(3, animation);

		}
		if (id == 4) {
			boolean is_check_imgtb5 = false;
			if (is_check_imgtb5 == true) {
				tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan);
				tab2.setBackgroundResource(R.drawable.ic_danhba);
				tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi);
				tab4.setBackgroundResource(R.drawable.ic_khach_hang);
				tab5.setBackgroundResource(R.drawable.tab_cai_dat);
				is_check_imgtb5 = false;
			} else {
				tab5.setBackgroundResource(R.drawable.ic_tab_caidat);
				tab1.setBackgroundResource(R.drawable.ic_tab_tinnhan);
				tab3.setBackgroundResource(R.drawable.ic_tab_ketnoi);
				tab4.setBackgroundResource(R.drawable.ic_khach_hang);
				tab2.setBackgroundResource(R.drawable.ic_danhba);
				is_check_imgtb5 = true;
			}
			viewPager.setCurrentItem(4, animation);
		}

	}

	private void setChecked1(int id) {
		try {
			TabIcon[] tabs = { tab1, tab2, tab3, tab4, tab5 };
			viewPager.setCurrentItem(id);
			for (int i = 0; i < tabs.length; i++) {
				if (id != i) {
					tabs[i].setChecked(false);
				} else {
					tabs[i].setChecked(true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tab1:
			chuyentab(0);

			break;
		case R.id.tab2:
			chuyentab(1);
			break;
		case R.id.tab3:
			chuyentab(2);
			break;
		case R.id.tab4:
			chuyentab(3);
			break;
		case R.id.tab5:
			chuyentab(4);
			break;

		default:
			break;
		}
	}

	class MyAdapter extends FragmentPagerAdapter {

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			// super.destroyItem(container, position, object);
		}

		public MyAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int i) {
			switch (i) {
			case 0:
				return new TinNhanScr();
			case 1:
				return new DanhbaScr();
			case 2:
				return new KetnoiScr();
			case 3:
				return new KhachhangScr();
			case 4:
				return new CaidatScr();
			default:
				return new TinNhanScr();
			}
		}

		@Override
		public int getCount() {
			return 5;
		}

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int id) {
		chuyentab(id);
	}

	public void invalidateViewPager() {
		if (viewPager != null)
			viewPager.invalidate();
	}

	public boolean isSocketConnected() {
		if (socketIO == null)
			return false;
		return socketIO.isConnected();
	}

	public void StopSocket() {
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				disConnectSocket();

			}
		}, 2000);
	}

	private void disConnectSocket() {
		if (socketIO != null && socketIO.isConnected() && !Common.appRunning) {
			try {
				if (tr != null) {
					tr.interrupt();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			try {
				if (socketIO != null) {
					socketIO.disconnect();
				}
			} catch (Exception e) {
			}

		}
	}

	public static MainPanelActivity getInstance() {
		return me;
	}

	public void startSocket() {
		if (socketIO != null && !socketIO.isConnected())
			connectSocket();
	}
	// khong tư dong check 3s
	public void stopAutoConnect() {
		mHandler.removeCallbacks(checkConnect);
		
	}
	
	public void startAutoConnect(){
		mHandler.removeCallbacks(checkConnect);
		mHandler.postDelayed(checkConnect,3000);
	}
	
	

}
